package com.primaryedu.ui.app.classadjust;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.adapter.ClassAdjustAdapter;
import com.primaryedu.bean.ClassBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.widget.MyListView;
import com.primaryedu.widget.PullToRefreshView;
import com.primaryedu.widget.PullToRefreshView.OnFooterRefreshListener;
import com.primaryedu.widget.PullToRefreshView.OnHeaderRefreshListener;

import javax.microedition.khronos.opengles.GL;

/**
 * 应用中心--课务调整
 *
 * @author jun.wang
 * @description
 * @data 2017年12月11日
 */
public class ClassAdjustActivity extends BaseActivity implements OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
    private ListView listView;
    ClassAdjustAdapter adapter;
    private TextView text_one, text_two;
    private boolean fistenter = true;
    private final static int REQUESTCODEAPPROVE = 2; // "申请"返回的结果码
    private final static int REQUESTCODELEAVE = 1; // "申请"返回的结果码
    private int page = 1;
    private PullToRefreshView pullToRefreshView;
    private List<ClassBean> list = new ArrayList<>();
    private List<ClassBean> tempList = new ArrayList<>();

    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != tempList && tempList.size() != 0) {
                        adapter = new ClassAdjustAdapter(ClassAdjustActivity.this, tempList);
                        listView.setAdapter(adapter);
                    }
                    break;
                case 1002:
                    if (tempList != null && tempList.size() != 0) {
                        adapter.updateView(tempList);
                    }
                default:
                    break;
            }
        }

        ;
    };


    @Override
    protected int BindLayout() {
        return R.layout.activity_class_adjust;
    }

    @Override
    protected void initView() {
        ((TextView) findViewById(R.id.title)).setText("课务调整");
        findViewById(R.id.back).setOnClickListener(this);
        listView = (MyListView) this.findViewById(R.id.listView);
        findViewById(R.id.right).setVisibility(View.VISIBLE);
        findViewById(R.id.right).setOnClickListener(this);
        ((TextView) findViewById(R.id.text_right)).setText("申请调课");

        text_one = (TextView) this.findViewById(R.id.text_one);
        text_two = (TextView) this.findViewById(R.id.text_two);
        text_one.setOnClickListener(this);
        text_two.setOnClickListener(this);

        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
//				showToast(""+tempList.get(position).getRemarks());
                ClassBean cb = tempList.get(position);
                if (GlobalData.getUsertype(getApplicationContext()).contains("9")) {
//						|| GlobalData.accountBean.getuserType().contains("7")){//管理员 7:校长 9：调课管理员
                    Intent intent = new Intent(ClassAdjustActivity.this, ClassApproveActivtiy.class);
                    intent.putExtra("id", cb.getId());
                    intent.putExtra("staus", cb.getStatus());
                    intent.putExtra("remarks", cb.getRemarks());
                    intent.putExtra("auditorname", cb.getAuditorName());
                    startActivityForResult(intent, REQUESTCODEAPPROVE);
                } else {//普通用户
//					Toast.makeText(LeaveListActivity.this,"普通用户",Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(ClassAdjustActivity.this, ClassDetailsActivtiy.class);
                    intent.putExtra("staus", cb.getStatus());
                    intent.putExtra("id", cb.getId());
                    intent.putExtra("auditorname", cb.getAuditorName());
                    intent.putExtra("remarks", cb.getRemarks());
                    startActivity(intent);
                }
            }
        });

        pullToRefreshView = (PullToRefreshView) this.findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());
    }

    @Override
    protected void initData() {
        requestData(fistenter);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                finish();
                break;

            case R.id.right:
                Intent intent = new Intent(ClassAdjustActivity.this, ClassAdjustDetailsActivity.class);
                startActivity(intent);
                break;

            case R.id.text_one:
                text_one.setTextColor(getResources().getColor(R.color.white));
                text_one.setBackgroundResource(R.drawable.icon_text_blue);
                text_two.setTextColor(getResources().getColor(R.color.main_button));
                text_two.setBackgroundResource(R.drawable.icon_pic_white);
                break;

            case R.id.text_two:
                text_one.setTextColor(getResources().getColor(R.color.main_button));
                text_one.setBackgroundResource(R.drawable.icon_text_white);
                text_two.setTextColor(getResources().getColor(R.color.white));
                text_two.setBackgroundResource(R.drawable.icon_pic_blue);
                break;

            default:
                break;
        }
    }

    private void requestData(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        page = 1;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getPageTableListJson,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("getclassListJson==" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                list = new Gson().fromJson(listStr,
                                        new TypeToken<List<ClassBean>>() {
                                        }.getType());
                                tempList.clear();
                                tempList.addAll(list);
                                handler.sendEmptyMessage(1001);
                                System.out.println("getNotice==" + list);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("加载失败，请下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                if (GlobalData.getUsertype(getApplicationContext()).contains("9")
                        || GlobalData.getUsertype(getApplicationContext()).contains("7")) {
                    //9：调课管理员  7：校长   (不传用参数createBy.id)
                } else {
                    map.put("createBy.id", GlobalData.getUserId(getApplicationContext()));
                }
                return map;
            }
        };
        requestQueue.add(stringRequest);

    }

    private void requestLeavemorelist() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getPageTableListJson,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=classmorelist=" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            if (result == 1) {
                                String data = json.getString("data");
                                if (data.contains("list")) {
                                    JSONObject listObj = new JSONObject(data);
                                    String listStr = listObj.getString("list");
                                    System.out.println("response=listStr=" + listStr);
                                    list = new Gson().fromJson(listStr,
                                            new TypeToken<List<ClassBean>>() {
                                            }.getType());

                                    tempList.addAll(list);
                                    handler.sendEmptyMessage(1002);
                                } else {
                                    showToast("已经加载完全部数据！");
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                if (GlobalData.getUsertype(getApplicationContext()).contains("9")
                        || GlobalData.getUsertype(getApplicationContext()).contains("7")) {
                    //9：调课管理员  7：校长   (不传用参数createBy.id)
                } else {
                    map.put("createBy.id", GlobalData.getUserId(getApplicationContext()));
                }
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                requestLeavemorelist();
                pullToRefreshView.onFooterRefreshComplete();
            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestData(false);
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(ClassAdjustActivity.this, "数据刷新完成!", Toast.LENGTH_LONG).show();
            }

        }, 1500);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 3) {
            if (requestCode == REQUESTCODELEAVE) {
                requestData(true);
            }
            if (requestCode == REQUESTCODEAPPROVE) {
                requestData(true);
            }
        }
    }
}
